import re
import logging
from typing import Dict, Optional
from utils.db_manager import DBManager

class TermProcessor:
    """专业术语处理类"""
    
    def __init__(self, source_lang: str, target_lang: str):
        self.logger = logging.getLogger(self.__class__.__name__)
        self.source_lang = source_lang
        self.target_lang = target_lang
        self.db_manager = DBManager()
        self.terms = self._load_terms()
        
    def _load_terms(self) -> Dict[str, str]:
        """从数据库加载术语"""
        return self.db_manager.load_technical_terms(
            self.source_lang,
            self.target_lang
        )
    
    def process_text(self, text: str) -> str:
        """处理文本中的专业术语"""
        if not text or not text.strip():
            return text
            
        processed_text = text
        self.logger.debug(f"Processing technical terms for: {text[:50]}...")
        
        try:
            # 1. 预处理：规范化空格
            processed_text = re.sub(r'\s+', ' ', processed_text).strip()
            
            # 2. 按长度排序术语（优先处理较长的术语）
            terms = sorted(
                self.terms.items(),
                key=lambda x: len(x[0]),
                reverse=True
            )
            
            # 3. 替换术语
            for source_term, target_term in terms:
                # 对于中文术语，直接替换
                if '\u4e00' <= source_term[0] <= '\u9fff':
                    before = processed_text
                    processed_text = processed_text.replace(source_term, target_term)
                    if before != processed_text:
                        self.logger.debug(f"Replaced '{source_term}' with '{target_term}'")
                else:
                    # 对于英文术语，使用词边界匹配
                    pattern = re.compile(r'\b' + re.escape(source_term) + r'\b', re.IGNORECASE)
                    before = processed_text
                    processed_text = pattern.sub(target_term, processed_text)
                    if before != processed_text:
                        self.logger.debug(f"Replaced '{source_term}' with '{target_term}'")
            
            # 4. 后处理：修复格式
            processed_text = re.sub(r'\s+', ' ', processed_text)  # 移除多余空格
            processed_text = re.sub(r'([。！？，、；：])\s+', r'\1', processed_text)  # 修复中文标点
            processed_text = re.sub(r'\s+([。！？，、；：])', r'\1', processed_text)  # 修复中文标点前的空格
            processed_text = processed_text.strip()
            
            return processed_text
            
        except Exception as e:
            self.logger.error(f"Term processing failed: {str(e)}")
            return text  # 出错时返回原文 